package cn.itcast.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <h4>day01_1_springcloud_eureka</h4>
 * <p>自定義過濾器</p>
 *
 * @author : by wujianming
 * @date : 2021-11-21 20:32
 **/
@Component
@Order(-1)//過濾器優先級--數值越小優先級越高
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //獲取請求參數
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        String authorization = queryParams.getFirst("authorization");
        //如果相等放行
        if ("admin".equals(authorization)) {
            return chain.filter(exchange);
        }
//        http://localhost:10010/user/1?authorization=admin必須携帶參數才放行
        //攔截禁止訪問
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
    }
}
